/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.admin;

import cn.easyplatform.cfg.RowLockProvider;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.type.IResponseMessage;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.cache.Cache;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


public class TableCmd extends AbstractCommand<SimpleRequestMessage> {
    /**
     * @param req
     */
    public TableCmd(SimpleRequestMessage req) {
        super(req);
    }

    @Override
    public IResponseMessage<?> execute(CommandContext cc) {
        if ("init".equals(req.getBody())) {
            return new SimpleResponseMessage(new List[]{cc.getIdGenerator().getList(), getLockInfo(cc)});
        } else if ("Seq".equals(req.getBody())) {
            return new SimpleResponseMessage(cc.getIdGenerator().getList());
        } else if ("Lock".equals(req.getBody())) {
            return new SimpleResponseMessage(getLockInfo(cc));
        } else {
            Object[] data = (Object[]) req.getBody();
            if (data.length == 6) {//lock
                cc.getSync().unlock(data[0] + ":" + data[1]);
            } else {
                cc.getIdGenerator().reset((String) data[0], ((Number) data[1]).longValue());
            }
        }
        return new SimpleResponseMessage();
    }

    private List<Object[]> getLockInfo(CommandContext cc) {
        Cache<Serializable, RowLockProvider.LockInfo> locks = cc.getProjectService().getCache("RowLocker");
        Collection<RowLockProvider.LockInfo> values = locks.values();
        List<Object[]> data = new ArrayList<>(values.size());
        values.forEach(rec -> {
            Object[] info = new Object[6];
            info[0] = StringUtils.substringBefore(rec.getKey(), ":");//table
            info[1] = StringUtils.substringAfter(rec.getKey(), ":");//key
            info[2] = rec.getUserId();
            info[3] = rec.getTaskId();
            info[4] = rec.getLayer();
            info[5] = rec.getFunId();
            data.add(info);
        });
        return data;
    }
}
